﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace HCPDemo
{
   
    public class HCPFileService
    {
        static string HCPUserName = ConfigurationManager.AppSettings["HCPUserName"].ToString();
        static string HCPPassword = ConfigurationManager.AppSettings["HCPPassword"].ToString();
        static string EncodeingType = "utf-8";
        static string HCPRestUrl = ConfigurationManager.AppSettings["HCPRestUrl"].ToString();
        static string HCPQuery = ConfigurationManager.AppSettings["HCPQuery"].ToString();
        

        public HCPFileService()
        {
           
        }

      

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="targetPath">目标路径</param>
        /// <param name="inFileDir">需要写入的文件路径</param>
        public static void WriteObject(string targetPath, string inFileDir)
        {
            //允许ssl连接的任何证书
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            //设置请求的路径和其他参数
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HCPRestUrl + targetPath);
            request.Method = WebRequestMethods.Http.Put;
            request.AllowWriteStreamBuffering = false;
            request.SendChunked = true;
            request.AllowAutoRedirect = false;  // Important because authentication error causes a redirect to occur.

            //设置访问凭据信息
            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

            //写入文件流
            using (Stream dataStream = request.GetRequestStream())
            {
                using (FileStream fileStreamToRead = System.IO.File.OpenRead(inFileDir))
                {
                    fileStreamToRead.CopyTo(dataStream); 
                }
            }

            //获取http响应并对响应进行处理
            try
            {

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.Created:
                        break;
                    case HttpStatusCode.Found:
                        response.Close();
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close(); 
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }
                response.Close();
            }
            catch (WebException ex)
            {
                
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }


        /// <summary>
        /// 写入文件，通过HttpPostedFileBase传输文件流
        /// </summary>
        /// <param name="targetPath">目标路径</param>
        /// <param name="file">HttpPostedFileBase</param>
        public static void WriteObject(string targetPath, HttpPostedFileBase file)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HCPRestUrl + targetPath);
            request.Method = WebRequestMethods.Http.Put;
            request.AllowWriteStreamBuffering = false;
            request.SendChunked = true;

            request.AllowAutoRedirect = false; 

            //设置访问凭据信息
            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);

            //string sHeader = "AD lindanyang@sist.org.cn:lindy@123";
            request.Headers.Add("Authorization", sHeader);

           
            using (Stream dataStream = request.GetRequestStream())
            {

                file.InputStream.CopyTo(dataStream); 
               
            }
            try
            {

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.Created:
                      
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close();
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }
                response.Close();
            }
            catch (WebException ex)
            {
          
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }


    
        /// <summary>
        /// 写入自定义元数据
        /// </summary>
        /// <param name="inFileDir">目标路径</param>
        /// <param name="fileMetadata">元数据信息，符合xml结构的string数据</param>
        public static void WriteObjectMetadata(string inFileDir, string fileMetadata)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            UriBuilder myURI = new UriBuilder(HCPRestUrl + inFileDir);
            myURI.Query = "type=custom-metadata";

            byte[] bytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(fileMetadata);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Put;

            request.AllowAutoRedirect = false;  

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

            using (Stream requestStream=request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.Created:
                        
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close();
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

              
                response.Close();
            }
            catch (WebException ex)
            {
                
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }


       

        /// <summary>
        /// 读取文件到流中
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="inFileDir"></param>
        public static void ReadObjectToSream(Stream stream, string inFileDir)
        {

            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HCPRestUrl + inFileDir);
            request.Method = WebRequestMethods.Http.Get;

            request.AllowAutoRedirect = false; 

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

          
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.Found:
                        response.Close();
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close(); 
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }


                using (Stream responseStream = response.GetResponseStream())
                {
                        responseStream.CopyTo(stream);
                }
                response.Close();
            }
            catch (WebException ex)
            {
                
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Found:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }



        /// <summary>
        /// 读取元数据信息，返回内容为符合xml格式的string
        /// </summary>
        /// <param name="inFileDir"></param>
        /// <returns></returns>
        public static string ReadObjectMetadata(string inFileDir)
        {

            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            string result = "";

            UriBuilder myURI = new UriBuilder(HCPRestUrl + inFileDir);
            myURI.Query = "type=custom-metadata";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Get;

            request.AllowAutoRedirect = false; 

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);
            try
            {
               
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.Found:
                        response.Close();
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close(); 
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {

                }
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(EncodeingType));
                    result = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    request.Abort();
                    
                }
                response.Close();
            }
            catch (WebException ex)
            {
               
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Found:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }

            return result;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="inFileDir"></param>
        public static void DeleteObject(string inFileDir)
        {


            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HCPRestUrl +inFileDir);
            request.Method = "DELETE";

            request.AllowAutoRedirect = false;  

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

            try
            {
              
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close(); 
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

              
                response.Close();
            }
            catch (WebException ex)
            {
                
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }

        /// <summary>
        /// 创建路径
        /// </summary>
        /// <param name="Dir"></param>
        public static void CreateDirPath(string Dir)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            UriBuilder myURI = new UriBuilder(HCPRestUrl + Dir);
            myURI.Query = "type=directory";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Put;

            request.AllowAutoRedirect = false; 

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

      
            try
            {
                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.Created:
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close();
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }
              
                response.Close();
            }
            catch (WebException ex)
            {
                
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Found:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex;
            }
        }

        /// <summary>
        /// 检查路径是否存在，httpmethod=head
        /// </summary>
        /// <param name="Dir"></param>
        public static void CheckDirPath(string Dir)
        {

            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            UriBuilder myURI = new UriBuilder(HCPRestUrl + Dir);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Head;

            request.AllowAutoRedirect = false;  

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.NotFound:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close();
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

                response.Close();
            }
            catch (WebException ex)
            {
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 
                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.NotFound:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }
        }


        /// <summary>
        /// 获取路径下面的内容，返回内容为符合xml格式的string
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="deleted"></param>
        /// <returns></returns>
        public static string ListDirContents(string dir, bool deleted = false)
        {
            string result = "";
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            UriBuilder myURI = new UriBuilder(HCPRestUrl + dir);
            if (deleted)
            {
                myURI.Query = "deleted=true";
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Get;

            request.AllowAutoRedirect = false; 

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);
          
            try
            {
                // Execute the request.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close();
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {

                }
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(EncodeingType));
                    result = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    request.Abort();

                }

                
                response.Close();
            }
            catch (WebException ex)
            {
          
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Found:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }

            return result;
        }

        /// <summary>
        /// 搜索文件，返回内容为符合json格式的string
        /// </summary>
        /// <param name="searchdata"></param>
        /// <returns></returns>
        public static string SearchFiles(string searchdata)
        {
            string result = "";
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            UriBuilder myURI = new UriBuilder(HCPQuery);
          
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myURI.Uri);
            request.Method = WebRequestMethods.Http.Post;

            request.ContentType = "application/json;charset=UTF-8";

            request.AllowAutoRedirect = false;  

            request.Accept = "application/json;charset=UTF-8";

            string sHeader = "HCP " + Base64Encode(HCPUserName) + ":" + MD5Encode(HCPPassword);
            request.Headers.Add("Authorization", sHeader);

            byte[] bytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(searchdata);

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        Console.WriteLine("File Retrieved");
                        break;
                    case HttpStatusCode.Found:
                        response.Close(); 
                        throw new WebException("Authentication Failure with HCP. HttpStatus: " + response.StatusCode + " (" + response.StatusDescription + ")");
                    default:
                        response.Close(); 
                        throw new WebException("Unexpected HTTP Response Code: " + response.StatusCode + " (" + response.StatusDescription + ")");
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {

                }
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(EncodeingType));
                    result = reader.ReadToEnd();
                    responseStream.Close();
                    request.Abort();

                }
                response.Close();
            }
            catch (WebException ex)
            {
               
                if (null != ex.Response)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    String statusDescription = response.StatusDescription;

                    response.Close(); 

                    switch (statusCode)
                    {
                        case HttpStatusCode.Conflict:
                            throw new WebException("Object already exists on HCP. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Found:
                            throw new WebException("Object does not exist. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                        case HttpStatusCode.Forbidden:
                            throw new WebException("Operation requested is not allowed. HttpStatus: " + statusCode + " (" + statusDescription + ")");
                    }
                }

                throw ex; 
            }

            return result;
        }


        #region helper
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="inString"></param>
        /// <returns></returns>
        static String MD5Encode(String inString)
        {
            MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider();

            byte[] tBytes = Encoding.ASCII.GetBytes(inString);
            byte[] hBytes = hasher.ComputeHash(tBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hBytes.Length; i++)
                sb.AppendFormat("{0:x2}", hBytes[i]);

            return sb.ToString();
        }

        /// <summary>
        /// base64编码
        /// </summary>
        /// <param name="inString"></param>
        /// <returns></returns>
        static String Base64Encode(String inString)
        {
            byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(inString);

            return System.Convert.ToBase64String(toEncodeAsBytes);
        }

        static public bool AcceptAllCertifications(object sender,
            System.Security.Cryptography.X509Certificates.X509Certificate certification,
            System.Security.Cryptography.X509Certificates.X509Chain chain,
            System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        #endregion 

    }
}

